package handlers

import (
	"fmt"
	"net/http"
	"ssr/common"
	"ssr/dto"
	service "ssr/services"

	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
)

type LinkHandler struct {
	linkService *service.LinkService
}

func NewLinkHandler() *LinkHandler {
	return &LinkHandler{
		linkService: service.NewLinkService(),
	}
}

func (h *LinkHandler) CreateLink(c *gin.Context) {
	var createLink dto.CreateLinkDto
	if err := c.ShouldBindWith(&createLink, binding.FormPost); err != nil {
		c.Set("already_sent", true)
		common.Fail(http.StatusBadRequest, err.Error()).Send(c)
		return
	}
	// var fileNames []string
	form, _ := c.MultipartForm()
	files := form.File["attachments"]

	for _, file := range files {
		fileName := fmt.Sprintf("uploads/%s", file.Filename)
		fmt.Println(file.Filename, fileName)
		// if err := c.SaveUploadedFile(file, fileName); err != nil {
		// 	c.JSON(http.StatusInternalServerError, gin.H{"error": "文件保存失败"})
		// 	return
		// }
		// fileNames = append(fileNames, fileName)
	}

	link, err := h.linkService.CreateLink(createLink)
	if err != nil {
		c.Set("already_sent", true)
		common.Fail(http.StatusBadRequest, err.Error()).Send(c)
	}
	common.Success(link).Send(c)
}
